using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TangHotKey.Demo
{
    public partial class MainForm : Form
    {
        private List<int> registeredHotKeyIds = new List<int>();

        public MainForm()
        {
            InitializeComponent();
            InitializeHotKeys();
            LoadConfigAndRegisterHotKeys();
        }

        private void InitializeHotKeys()
        {
            // 初始化全局热键管理器
            GlobalHotKey.Initialize(this);
            UpdateStatus("热键管理器已初始化");
            RefreshHotKeyList();
        }

        private void LoadConfigAndRegisterHotKeys()
        {
            // 加载配置文件
            bool configLoaded = HotKeyConfig.LoadConfig();
            UpdateStatus(configLoaded ? "配置文件加载成功" : "使用默认配置");
            
            // 注册热键
            RegisterHotKeysFromConfig();
        }
        
        private void RegisterHotKeysFromConfig()
        {
            // 自动注册保存的热键
            foreach (var hotKeyItem in HotKeyConfig.Current.HotKeys)
            {
                if (hotKeyItem.IsEnabled)
                {
                    var hotKey = new HotKeyCombination(hotKeyItem.Modifiers, hotKeyItem.Key, hotKeyItem.Description);
                    int id = hotKey.Register(() =>
                    {
                        // 更新最后使用时间
                        HotKeyConfig.UpdateLastUsedTime(hotKeyItem.Modifiers, hotKeyItem.Key);
                        
                        MessageBox.Show($"热键 {hotKey} 被触发！\n\n描述: {hotKeyItem.Description}", 
                            "TangHotKey Demo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        UpdateStatus($"热键 {hotKey} 被触发");
                    });
                    
                    if (id != -1)
                    {
                        registeredHotKeyIds.Add(id);
                    }
                }
            }
            
            RefreshHotKeyList();
            UpdateStatus($"已加载 {HotKeyConfig.Current.HotKeys.Count} 个热键配置");
        }

        private void buttonEdit_Click(object sender, EventArgs e)
        {
            var editForm = new HotKeyEditForm();
            editForm.HotKeyRegistered += EditForm_HotKeyRegistered;
            editForm.ShowDialog(this);
        }

        private void EditForm_HotKeyRegistered(object sender, HotKeyRegisteredEventArgs e)
        {
            var hotKey = new HotKeyCombination(e.Modifiers, e.Key, e.Description);
            int id = hotKey.Register(() =>
            {
                // 更新最后使用时间
                HotKeyConfig.UpdateLastUsedTime(e.Modifiers, e.Key);
                
                MessageBox.Show($"热键 {hotKey} 被触发！\n\n描述: {e.Description}", 
                    "TangHotKey Demo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                UpdateStatus($"热键 {hotKey} 被触发");
            });

            if (id != -1)
            {
                registeredHotKeyIds.Add(id);
                
                // 保存到配置文件
                HotKeyConfig.AddHotKey(e.Modifiers, e.Key, e.Description);
                
                UpdateStatus($"成功注册热键: {hotKey}");
                RefreshHotKeyList();
            }
            else
            {
                UpdateStatus("注册热键失败，可能已被其他程序占用");
                MessageBox.Show($"注册热键 {hotKey} 失败！\n\n可能原因：\n1. 热键已被其他程序占用\n2. 系统不允许注册此热键", 
                    "注册失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void buttonRemoveSelected_Click(object sender, EventArgs e)
        {
            if (listBoxHotKeys.SelectedItem == null)
            {
                MessageBox.Show("请先选择要删除的热键！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var selectedText = listBoxHotKeys.SelectedItem.ToString();
            if (selectedText.StartsWith("ID: "))
            {
                // 提取热键ID
                var parts = selectedText.Split(' ');
                if (parts.Length >= 2 && int.TryParse(parts[1], out int hotKeyId))
                {
                    // 获取要删除的热键信息
                    var hotKeyInfo = GlobalHotKey.GetRegisteredHotKeys().FirstOrDefault(h => h.Id == hotKeyId);
                    
                    if (GlobalHotKey.Unregister(hotKeyId))
                    {
                        registeredHotKeyIds.Remove(hotKeyId);
                        
                        // 从配置文件中删除
                        if (hotKeyInfo != null)
                        {
                            HotKeyConfig.RemoveHotKey(hotKeyInfo.Modifiers, hotKeyInfo.Key);
                        }
                        
                        UpdateStatus($"已删除热键 ID: {hotKeyId}");
                        RefreshHotKeyList();
                    }
                    else
                    {
                        UpdateStatus($"删除热键失败 ID: {hotKeyId}");
                    }
                }
            }
        }

        private void buttonClearAll_Click(object sender, EventArgs e)
        {
            var result = MessageBox.Show("确定要清除所有热键吗？这将删除所有保存的热键配置。", 
                "确认清除", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            
            if (result == DialogResult.Yes)
            {
                foreach (int id in registeredHotKeyIds)
                {
                    GlobalHotKey.Unregister(id);
                }
                registeredHotKeyIds.Clear();
                
                // 清除配置文件中的所有热键
                HotKeyConfig.ClearAllHotKeys();
                
                UpdateStatus("所有热键已清除");
                RefreshHotKeyList();
            }
        }

        private void RefreshHotKeyList()
        {
            listBoxHotKeys.Items.Clear();
            var hotKeys = GlobalHotKey.GetRegisteredHotKeys();
            
            if (hotKeys.Count == 0)
            {
                listBoxHotKeys.Items.Add("当前没有注册的热键");
            }
            else
            {
                listBoxHotKeys.Items.Add($"已注册 {hotKeys.Count} 个热键:");
                listBoxHotKeys.Items.Add("");
                
                foreach (var hotKey in hotKeys)
                {
                    var combination = new HotKeyCombination(hotKey.Modifiers, hotKey.Key, hotKey.Description);
                    listBoxHotKeys.Items.Add($"ID: {hotKey.Id} - {combination}");
                }
            }
        }

        private void UpdateStatus(string message)
        {
            labelStatus.Text = $"状态：{message}";
            // 可以添加日志记录
            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss}] {message}");
        }

        private void buttonExportConfig_Click(object sender, EventArgs e)
        {
            using (var saveFileDialog = new SaveFileDialog())
            {
                saveFileDialog.Filter = "JSON配置文件 (*.json)|*.json|所有文件 (*.*)|*.*";
                saveFileDialog.Title = "导出热键配置";
                saveFileDialog.FileName = $"TangHotKey_Config_{DateTime.Now:yyyyMMdd_HHmmss}.json";
                
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    if (HotKeyConfig.ExportConfig(saveFileDialog.FileName))
                    {
                        UpdateStatus($"配置已导出到: {saveFileDialog.FileName}");
                        MessageBox.Show("配置导出成功！", "导出完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        UpdateStatus("配置导出失败");
                        MessageBox.Show("配置导出失败，请检查文件路径和权限。", "导出失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
        
        private void buttonImportConfig_Click(object sender, EventArgs e)
        {
            using (var openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "JSON配置文件 (*.json)|*.json|所有文件 (*.*)|*.*";
                openFileDialog.Title = "导入热键配置";
                
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    var result = MessageBox.Show("导入配置将替换当前所有热键设置，是否继续？", 
                        "确认导入", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    
                    if (result == DialogResult.Yes)
                    {
                        // 先清除当前所有热键
                        foreach (int id in registeredHotKeyIds)
                        {
                            GlobalHotKey.Unregister(id);
                        }
                        registeredHotKeyIds.Clear();
                        
                        // 导入新配置
                         if (HotKeyConfig.ImportConfig(openFileDialog.FileName))
                         {
                             // 重新注册热键
                             RegisterHotKeysFromConfig();
                             UpdateStatus($"配置已从 {openFileDialog.FileName} 导入");
                             MessageBox.Show("配置导入成功！", "导入完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                         }
                        else
                        {
                            UpdateStatus("配置导入失败");
                            MessageBox.Show("配置导入失败，请检查文件格式是否正确。", "导入失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 保存配置文件
            bool configSaved = HotKeyConfig.SaveConfig();
            if (configSaved)
            {
                UpdateStatus("配置已保存");
            }
            
            // 清理资源
            GlobalHotKey.Cleanup();
            UpdateStatus("程序正在退出，热键已清理");
        }
    }
}
